﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebHoiChoMuaBan.Models;
using WebHoiChoMuaBan.Controllers.Helpers;
using WebHoiChoMuaBan.Controllers.Utility;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.Routing;
using WebHoiChoMuaBan.Controllers.Global;

namespace WebHoiChoMuaBan.Controllers.Admin
{
    public class AdminNewsController : AdminController
    {

        [HttpGet]
        public ActionResult Index(int? newsTypeId)
        {
            if (IsLogin && checkRight())
            {
                if ((bool)ViewData["IsOwner"])
                {
                    int pageNum;
                    if (!int.TryParse(Request.QueryString["p"], out pageNum))
                        pageNum = 1;
                    NewsHelper newsHelper = new NewsHelper();
                    ViewData["NewsList"] = newsHelper.getListNews_Admin(pageNum, Config.ITEMS_PER_ADMINPAGE, newsTypeId);
                    ViewData["NewsTypeId"] = newsTypeId;
                    return View("~/Views/Admin/News.aspx");
                }
            }
            return HomeAdminPage();
        }


        public ActionResult ListNew(int? cateId)
        {
            if (IsLogin && checkRight())
            {
                if ((bool)ViewData["IsOwner"])
                {
                    ViewData["CateId"] = cateId;
                    int pageNum;
                    if (!int.TryParse(Request.QueryString["p"], out pageNum))
                        pageNum = 1;
                    else
                        pageNum = int.Parse(Request.QueryString["p"]);
                    NewsProductHelper newsProductHelper = new NewsProductHelper();
                    if (cateId == null)
                    {
                        CategoryHelper cateHelper = new CategoryHelper();
                        cateId = cateHelper.getRandomCategory();
                    }
                    ViewData["ListNewsProduct"] = newsProductHelper.AllNewsProductByCategory(pageNum, Config.ITEMS_PER_ADMINPAGE, cateId.Value);
                    return View("~/Views/Admin/New_List.aspx");
                }
            }
            return HomeAdminPage();
        }

        public ActionResult AddNews()
        {
            return View("~/Views/Admin/PostNews.aspx");
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult AddNews(FormCollection f, HttpPostedFileBase newsImg)
        {
            News news = new News();
            news.NewsTitle = f.Get("txtTitle");
            news.NewsIntro = f.Get("txtIntro");
            news.NewsContent = f.Get("txtContent");
            news.NewsDate = DateTime.Now;
            news.NewsState = false;
            if (newsImg != null)
            {
                ImageHelper imgHelper = new ImageHelper();
                if (imgHelper.CheckInfoIcon(newsImg))
                {
                    string imgName = "thumbnail_" + newsImg.FileName;
                    news.NewsThumb = imgName;
                    Bitmap image = imgHelper.ResizeImage(newsImg.InputStream, 200, 100);
                    var path = Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail/"), imgName);
                    image.Save(path);
                    image.Dispose();
                }
            }
            //Phân loại tin mới được tạo 
            news.NewsTypeId = int.Parse(f.Get("lstNewsType"));
            //Tin được tạo bởi member nào
            news.MemId = (int)Session["MemId"];

            ViewData["News"] = news;
            if (news.IsValid)
            {
                NewsHelper newsHelper = new NewsHelper();
                newsHelper.Add(news);
                newsHelper.Save();
                //Reset lại các trường ban đầu
                ViewData["News"] = null;
                return RedirectToAction("AddNews", "AdminNews");
            }
            else
            {
                foreach (var issue in news.GetRuleViolations())
                {
                    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                }
            }
            return View("~/Views/Admin/PostNews.aspx");
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult EditNews(FormCollection f, HttpPostedFileBase newsImg)
        {
            int newsId = int.Parse(f.Get("newsId"));
            NewsProductHelper newsHelper = new NewsProductHelper();
            NewsProduct newsToEdit = newsHelper.getNewsProductById(newsId);
            newsToEdit.NProTitle = f.Get("txtTitle");
            newsToEdit.NProIntro = f.Get("txtIntro");
            newsToEdit.NProContent = f.Get("txtContent");
            newsToEdit.NProDate = DateTime.Now;
            //newsToEdit.NewsState = false;
            if (newsImg != null)
            {
                //Xóa hình cũ trong trường hợp không null
                NewsProductThumb thumb = new NewsProductThumb();
                if (newsToEdit.NewsProductThumbs.Count != 0)
                    thumb = newsToEdit.NewsProductThumbs[0];
                string oldImg = "thumbnail_" + thumb.NProThumbName;
                ImageHelper imgHelper = new ImageHelper();

                if (!String.IsNullOrEmpty(oldImg))
                {
                    imgHelper.DeleteImg(Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail"), oldImg));
                }
                //Thêm hình mới
                if (imgHelper.CheckInfoIcon(newsImg))
                {
                    string imgName = "thumbnail_" + newsImg.FileName;
                    thumb.NProThumbName = imgName;
                    Bitmap image = imgHelper.ResizeImage(newsImg.InputStream, 200, 100);
                    var path = Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail"), imgName);
                    image.Save(path);
                    image.Dispose();
                }
            }


            //Phân loại tin mới được tạo 
            newsToEdit.CateId = int.Parse(f.Get("lstNewsType"));
            //Tin được tạo bởi member nào
            newsToEdit.MemId = (int)Session["MemId"];

            ViewData["News"] = newsToEdit;
            if (newsToEdit.IsValid)
            {
                newsHelper.Save();
                //Reset lại các trường ban đầu
                ViewData["News"] = null;
            }
            else
            {
                foreach (var issue in newsToEdit.GetRuleViolations())
                {
                    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                }
            }
            new NewsProductHelper().Save();
            return ListNew(newsToEdit.CateId);
        }

        [HttpGet]
        public ActionResult LoadNewsToEdit(int newsId)
        {
            if (IsLogin && checkRight())
            {
                if ((bool)ViewData["IsOwner"])
                {
                    NewsProductHelper newsHelper = new NewsProductHelper();
                    NewsProduct news = newsHelper.getNewsProductById(newsId);
                    ViewData["NewsToEdit"] = news;
                    return View("~/Views/Admin/EditNews.aspx");
                }
            }
            return HomeAdminPage();
        }

        [HttpGet]
        public ActionResult DeleteNews(int newsId)
        {
            if (IsLogin && checkRight())
            {
                if ((bool)ViewData["IsOwner"])
                {
                    NewsHelper newsHelper = new NewsHelper();
                    News news = newsHelper.GetNewsById(newsId);
                    int newsTypeId = news.NewsTypeId;
                    newsHelper.Delete(news);
                    newsHelper.Save();
                    return Index(newsTypeId);
                }
            }
            return HomeAdminPage();
        }

        [HttpPost]
        public ActionResult Controller(FormCollection data)
        {
            if (IsLogin && checkRight())
            {
                if ((bool)ViewData["IsOwner"])
                {
                    int pageNum = data.Get("p") == null ? 0 : int.Parse(data.Get("p"));
                    NewsHelper newsHelper = new NewsHelper();
                    String[] lstNewsId = data.GetValues("checkbox");
                    int newsTypeId = newsHelper.getNews(int.Parse(lstNewsId[0])).NewsTypeId;
                    //Click "xoa" button
                    if (data.Get("hidCmd").Equals("del"))
                    {
                        //Lưu lại trang đang đứng
                        if (lstNewsId != null)
                        {
                            foreach (string item in lstNewsId)
                            {
                                News news = newsHelper.GetNewsById(int.Parse(item));
                                newsHelper.Delete(news);
                                newsHelper.Save();
                            }
                        }
                        return Index(newsTypeId);
                    }

                    //Click "chuyen trang thai" button
                    if (data.Get("hidCmd").Equals("ChangeState"))
                    {
                        if (lstNewsId != null)
                        {
                            foreach (string item in lstNewsId)
                            {
                                News news = newsHelper.GetNewsById(int.Parse(item));
                                if (news != null)
                                {
                                    if (news.NewsState)
                                        news.NewsState = false;
                                    else
                                        news.NewsState = true;
                                }
                                newsHelper.Save();
                            }
                        }
                    }
                    return RedirectToAction("Index", "AdminNews", new { p = pageNum, newsTypeId = newsTypeId });
                }
            }
            return HomeAdminPage();
        }
    }
}
